package com.study.spmongodb.wwj.thread.char10;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;

/**
 * @author MI
 * @version 1.0
 * @date 2020/12/6 16:06
 */
public class BooleanLock implements Lock {
    private boolean initValue;

    private Collection<Thread> blockThreadCollection = new ArrayList<>();

    private Thread currentThread;

    public BooleanLock() {
        this.initValue = false;
    }

    @Override
    public synchronized void lock() throws InterruptedException {
        while (initValue) {
            blockThreadCollection.add(Thread.currentThread());
            this.wait();
        }
        this.initValue = true;
        this.currentThread = Thread.currentThread();
    }

    @Override
    public synchronized void lock(long mills) throws InterruptedException, TimeOutException {
        if (mills <= 0) {
            lock();
        }

        long hasRemaining = mills;
        long endTime = System.currentTimeMillis() + mills;
        while (initValue) {
            if (hasRemaining <= 0) {
                throw new TimeOutException("超时");
            }
            blockThreadCollection.add(Thread.currentThread());
            this.wait(mills);
            hasRemaining = System.currentTimeMillis() - endTime;
        }
        this.initValue = true;
        blockThreadCollection.remove(Thread.currentThread());
        this.currentThread = Thread.currentThread();

    }

    @Override
    public synchronized void unlock() {
        if (currentThread == Thread.currentThread()) {
            this.initValue = false;
            System.out.println(Thread.currentThread() + " release the lock");
            this.notifyAll();
        }
    }

    @Override
    public Collection<Thread> getBlockedThread() {
        return Collections.unmodifiableCollection(blockThreadCollection);
    }

    @Override
    public int getBlockSize() {
        return blockThreadCollection.size();
    }
}
